package com.agricultural.machine.chain;

import com.agricultural.machine.common.IMachine;
import com.agricultural.machine.factory.MachineFactory;
import com.agricultural.machine.path.PathOptimizer;
import com.agricultural.machine.path.PathPoint;
import com.agricultural.machine.path.TerrainData;

import java.util.ArrayList;
import java.util.List;

/**
 * 障碍物处理器类 - 责任链模式
 */
public class ObstacleHandler extends AbstractSafetyHandler {
    private final MachineFactory machineFactory;
    private final PathOptimizer pathOptimizer;
    
    public ObstacleHandler() {
        this.machineFactory = MachineFactory.getInstance();
        this.pathOptimizer = PathOptimizer.getInstance();
    }
    
    @Override
    public boolean handle(SafetyEvent event) {
        if (event.getEventType().equals("OBSTACLE")) {
            System.out.println("障碍物处理器处理事件: " + event.getDescription());
            
            // 获取农机
            IMachine machine = machineFactory.getMachine(event.getMachineId());
            if (machine == null) {
                System.out.println("无法找到农机: " + event.getMachineId());
                return false;
            }
            
            // 停止农机
            machine.stop();
            
            // 重新规划路径避开障碍物
            recalculatePath(machine);
            
            // 标记事件已处理
            event.setHandled(true);
            return true;
        }
        
        // 不是障碍物事件，传递给下一个处理器
        return handleNext(event);
    }
    
    /**
     * 重新计算路径
     */
    private void recalculatePath(IMachine machine) {
        System.out.println("为农机 " + machine.getMachineId() + " 重新规划路径避开障碍物");
        
        // 当前位置作为起点
        PathPoint start = new PathPoint(machine.getCurrentX(), machine.getCurrentY());
        
        // 假设终点
        PathPoint end = new PathPoint(start.x + 100, start.y + 100);
        
        // 创建原始路径
        List<PathPoint> originalPath = new ArrayList<>();
        originalPath.add(start);
        originalPath.add(end);
        
        // 创建地形数据
        TerrainData terrain = new TerrainData(
            500, 500, 5, 50, "坚硬"
        );
        
        // 获取其他农机路径用于避免冲突
        List<PathPoint> otherPaths = new ArrayList<>();
        
        // 使用绕行策略重新计算路径
        String originalStrategy = pathOptimizer.getCurrentPathStrategy().getName();
        pathOptimizer.setPathStrategy("avoidObstacle");
        
        pathOptimizer.optimizePath(machine.getMachineId(), originalPath, terrain, otherPaths);
        
        // 恢复原来的路径策略
        pathOptimizer.setPathStrategy(originalStrategy);
        
        System.out.println("路径重规划完成，农机可以继续行驶");
    }
}

















